package edu.xidian.bdilab.jrbigdata.util;

import com.google.common.base.Supplier;
import com.google.common.cache.Cache;
import com.google.common.cache.CacheBuilder;
import com.google.common.cache.RemovalListener;
import com.google.common.cache.RemovalNotification;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.util.StringUtils;

import java.util.List;
import java.util.concurrent.TimeUnit;

/**
 * Copyright: Copyright (c) 2017  zteits
 *
 * @ClassName: GuavaCacheUtil.java
 * @Description:
 * @version: v1.0.0
 * @author: wangfs
 * @date: 2021-05-21 09:50
 * Modification History:
 * Date             Author          Version            Description
 * ---------------------------------------------------------*
 * 2021-05-21     wangfs              v1.0.0               创建
 */

public class GuavaCacheUtil {

    private static final Logger log = LoggerFactory.getLogger(GuavaCacheUtil.class);

    /**
     * @desction: 使用google guava缓存处理
     */
    private static Cache<String,Object> cache;
    static {
        cache = CacheBuilder.newBuilder().maximumSize(10000)
                .expireAfterWrite(5, TimeUnit.MINUTES)
                .initialCapacity(10)
                .build();
    }

    /**
     * @desction: 获取缓存
     */
    public  static Object get(String key){
        return !StringUtils.isEmpty(key)?cache.getIfPresent(key):null;
    }
    /**
     * @desction: 放入缓存
     */
    public static void put(String key,Object value){
        if(!StringUtils.isEmpty(key) && value !=null){
            cache.put(key,value);
        }
    }
    /**
     * @desction: 移除缓存
     */
    public static void remove(String key){
        if(!StringUtils.isEmpty(key)){
            cache.invalidate(key);
        }
    }
    /**
     * @desction: 批量删除缓存
     */
    public static void remove(List<String> keys){
        if(keys !=null && keys.size() >0){
            cache.invalidateAll(keys);
        }
    }

    public static void main(String[] args) throws InterruptedException {
        GuavaCacheUtil.put("15029758498","123456");
        while (true){
            String value = (String)GuavaCacheUtil.get("15029758498");
            System.out.println(value);
            Thread.sleep(10000);
        }
    }
}